import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAUseContext';
import { IUseOAActionEnum } from '../common/useOAUseReducer';
import { materialTableService } from '../services/ModalServices';
import { Button, message } from 'antd';
import { getLoadMapList, getTenantID, onCloseModalCommon } from '@/utils';
import { showTotalInfo } from '@/common/constVariable';
import { UpdateTableCommon } from '../mconfig/UpdateTableCommon';
import { AssetacquisitionManageAPI } from '../common/type';
import _ from 'lodash';
import { ILoadMapTypeAll } from '@/common';
import { getUseAssetModalColumns } from '../mconfig/ModalColumns';

/** 领用 表单页 选择资产-模态框 */
export const OpenAssetModal: React.FC<AssetacquisitionManageAPI.IOpenMaterialModal> = ({
  onClose,
  isShowModal,
  queryType = '1',
  editState,
  editAssetId,
  handleEditSave,
}) => {
  /** 弹框的ref */
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /** 根样式 */
  const styleFixCls = 'contract-styfixcls-';

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //单位
  ]);

  /**  获取数据字典 */
  const midiList = loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`];

  /** 获取上下文 */
  const { curRes, useOADispatch, assetList } = useContext(ChangeControllerContext);

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, loadMdicMapObj, getManageData } = materialTableService(curRes, 1, queryType, editState, editAssetId);

  /** 暂时保存选中的值 */
  const [checkAssetList, setCheckAssetList] = useState<Record<string, any>[]>([]);

  /** 表格数据 */
  const [dataSource, setDataSource] = useState<Record<string, any>[]>([]);

  const dataRowMemo = useMemo(() => {
    let dataRow: Record<string, any>[] = [];
    if (data?.rows?.length >= 0) {
      dataRow = _.cloneDeep(data?.rows);
      // 添加总价和数量字段
      for (let i = 0; i < dataRow.length; i++) {
        dataRow[i].quantityOrArea = dataRow[i].hasOwnProperty('residueNum') ? dataRow[i].residueNum : dataRow[i].quantityOrArea;
        dataRow[i].materialOrAssetId = dataRow[i].id;
      }
      if (assetList.length !== 0) {
        for (let i = 0; i < assetList.length; i++) {
          let idx = dataRow.findIndex((item: Record<string, any>) => {
            return item.materialOrAssetId === assetList[i].materialOrAssetId;
          });
          if (idx !== -1) {
            dataRow[idx].quantityOrArea = Number(assetList[i].quantityOrArea);
            dataRow[idx].location = assetList[i].location;
            dataRow[idx].locationInfo = assetList[i].locationInfo;
          }
        }
      }
      setDataSource(dataRow);
    }
    return dataRow;
  }, [data]);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo) => {
    const tempArr = _.cloneDeep(dataSource);

    for (let i = 0; i < tempArr.length; i++) {
      tempArr[i].selected = selectInfo?.some((item) => item.id === tempArr[i].id);
    }
    setDataSource(tempArr);
    setCheckAssetList(selectInfo);
  };

  /** 初始化 */
  useEffect(() => {
    if (editState) {
      if (editAssetId?.text && Object.keys(editAssetId?.text).length !== 0) {
        let arr: Record<string, any>[] = [];
        for (let i = 0; i < Object.keys(editAssetId?.text).length; i++) {
          let idx: number = dataSource.findIndex((item: any) => {
            return item.id === Object.keys(editAssetId?.text)[i];
          });
          if (idx !== -1) {
            arr.push(dataSource[idx]);
          }
        }
        setCheckAssetList(arr);
      } else {
        setCheckAssetList([]);
      }
    } else {
      setCheckAssetList(assetList);
    }
  }, [isShowModal, loading]);

  /** 修改资产数量 */
  const changeNum = (id: string | number, value: string | number) => {
    /** 修改表格数量 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.id === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].quantityOrArea = value;
      setDataSource(arr);
    }

    /** 修改选中数量 */
    let checkIdx = checkAssetList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkAssetList);
      arr[checkIdx].quantityOrArea = value;
      if (arr[checkIdx].residueNum) {
        arr[checkIdx].expectNum = arr[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      } else {
        arr[checkIdx].expectNum = dataSource[checkIdx].residueNum - arr[checkIdx].quantityOrArea;
      }

      setCheckAssetList(arr);
    }
  };

  /** 修改存放地点 */
  const changeLocation = (id: string | number, value: string) => {
    /** 修改表格存放地点 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].location = value;
      setDataSource(arr);
    }

    /** 修改选中存放地点 */
    let checkIdx = checkAssetList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkAssetList);
      arr[checkIdx].location = value;
      setCheckAssetList(arr);
    }
  };

  /** 修改详细地址 */
  const changeLocationInfo = (id: string | number, value: string) => {
    /** 修改表格存放地点 */
    let idx = dataSource.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (idx !== -1) {
      let arr = _.cloneDeep(dataSource);
      arr[idx].locationInfo = value;
      setDataSource(arr);
    }

    /** 修改选中存放地点 */
    let checkIdx = checkAssetList.findIndex((item: Record<string, any>) => {
      return item.materialOrAssetId === id;
    });
    if (checkIdx !== -1) {
      let arr = _.cloneDeep(checkAssetList);
      arr[checkIdx].locationInfo = value;
      setCheckAssetList(arr);
    }
  };

  /** 点击确定 */
  const onSave = () => {
    if (checkAssetList && checkAssetList?.length > 0) {
      // 复核中选中的
      if (editState) {
        if (Object.keys(editAssetId).length !== 0) {
          let arr: any = JSON.parse(JSON.stringify(assetList));
          arr[editAssetId?.index].assetIds = {};
          for (let i = 0; i < checkAssetList.length; i++) {
            arr[editAssetId?.index].assetIds[checkAssetList[i].id] = checkAssetList[i].assetCode;
          }
          useOADispatch({
            type: IUseOAActionEnum.SELECT_ASSET,
            payload: arr,
          });
          handleEditSave(arr);
          onCloseModalCommon(updateModalRef);
        }
      } else {
        useOADispatch({
          type: IUseOAActionEnum.SELECT_ASSET,
          payload: [...checkAssetList],
        });
        onCloseModalCommon(updateModalRef);
      }
    } else {
      message.error('请至少选择一个资产');
    }
  };

  const [isNextBtn, setisNextBtn] = useState(true);

  const setisNextBtnFun = (isNextBtn: boolean) => {
    setisNextBtn(isNextBtn);
  };

  const desabledNextBtn = useMemo(() => {
    // 如果是复核中，则没有存放区域校验
    if (editState) {
      if (checkAssetList?.length != 0) {
        return false;
      } else {
        return true;
      }
    } else {
      if (
        checkAssetList?.length != 0 &&
        checkAssetList?.every((item: Record<string, any>) => item.location) &&
        checkAssetList?.every((item: Record<string, any>) => item.locationInfo) &&
        isNextBtn
      ) {
        return false;
      } else {
        return true;
      }
    }
  }, [checkAssetList, isNextBtn, editState]);

  const modelFooter = () => {
    return (
      <>
        <Button onClick={onSave} disabled={desabledNextBtn}>
          确定
        </Button>
      </>
    );
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={updateModalRef}
        title={'选择资产'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.7}
        bodyStyle={{
          height: document.body.clientHeight * 0.55,
          padding: 10,
        }}
        // onOk={onSave}
        footer={modelFooter()}
      >
        <UpdateTableCommon
          styleFixCls={styleFixCls}
          searchProps={{
            searchList,
            onReset,
            onSearch,
          }}
          selectTablePorps={{
            onSelectTable,
            selectRowObjList: checkAssetList,
            selectType: 'checkbox',
            setCheckRows: setCheckAssetList,
            getCheckboxProps: (record: Record<string, any>) => ({
              disabled: record.quantityOrArea <= 0,
            }),
          }}
          tableProps={{
            columns: getUseAssetModalColumns({
              changeLocation,
              changeLocationInfo,
              changeNum,
              setisNextBtnFun,
              queryType,
              editState,
              mapLoading,
              loadMapInfo,
              midiList,
            }),
            loading,
            dataSource: dataSource,
            pagination,
            onPageChange,
            rowKey: 'materialOrAssetId',
            tableTotalShow: (total: any, range: any) => {
              return (
                <div
                  style={{
                    display: 'flex',
                    width: '100%',
                    justifyContent: 'space-between',
                  }}
                >
                  <div>
                    已选择<strong style={{ color: 'red' }}> {checkAssetList?.length} </strong>条材料
                  </div>
                  <div>{showTotalInfo(total, range)}</div>
                </div>
              );
            },
          }}
        />
      </OneModal>
    </>
  );
};
